package com.lmk.mkcc.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.lmk.mkcc.domain.CourseOrder;
import com.lmk.mkcc.dto.PayextparamsDto;
import com.lmk.mkcc.enums.GlobalErrorCode;
import com.lmk.mkcc.service.ICourseOrderService;
import com.lmk.mkcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "pay-transaction-consumer-group",
        topic = "pay-transaction-topic",
        selectorExpression = "pay-transaction-tag",
        // 广播消息
        messageModel = MessageModel.BROADCASTING
)
public class PayAsyncNotifyConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private ICourseOrderService courseOrderService;
    @Override
    public void onMessage(MessageExt messageExt) {
        // 1.业务校验
        byte[] body = messageExt.getBody();
        // 2.类型转换，转为string
        String s = new String(body, StandardCharsets.UTF_8);
        // 3.将string转化为字符串
        PayextparamsDto payextparamsDto = JSON.parseObject(s, PayextparamsDto.class);
        // 4.非空判断
        AssertUtil.isNotNull(payextparamsDto, GlobalErrorCode.NO_DTO_ERROR);
        // 5.查询课程订单是否存在
        CourseOrder byorderNo = courseOrderService.getByorderNo(payextparamsDto.getOrderNo());
        // 6.非空判断
        if (byorderNo==null){
            log.info("课程订单不存在，订单号为：%s",payextparamsDto.getOrderNo());
            return;
        }
        // 7.判断课程订单状态
        if (CourseOrder.WAIT_PAY.equals(byorderNo.getStatusOrder())){
            // 修改课程订单状态
            byorderNo.setStatusOrder(CourseOrder.PAY_SUCCESS);
            byorderNo.setUpdateTime(new Date());
            courseOrderService.updateById(byorderNo);
        }


    }
}
